ReactJS Ultra For Beginners
🔄 The useReducer Hook
What is useReducer?
- A React Hook for managing complex state logic
- Alternative to useState when state logic is complex
- Based on the reducer pattern (like Redux)
- Takes a reducer function and initial state
📝 Basic Syntax
import { useReducer } from "react"; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; case "reset": return { count: 0 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> ); }
🔑 Core Concepts
1. Reducer Function:
function reducer(state, action) { switch (action.type) { case "ADD_TODO": return { ...state, todos: [...state.todos, action.payload], }; case "TOGGLE_TODO": return { ...state, todos: state.todos.map((todo) => todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo ), }; case "DELETE_TODO": return { ...state, todos: state.todos.filter((todo) => todo.id !== action.payload), }; default: return state; } }
2. Initial State:
const initialState = { todos: [], filter: "all", }; const [state, dispatch] = useReducer(reducer, initialState);
3. Dispatch Actions:
// Simple action dispatch({ type: "ADD_TODO", payload: newTodo }); // Action with payload dispatch({ type: "UPDATE_USER", payload: { id: 1, name: "John" }, });
🎯 Common Patterns
Todo List Example:
const initialState = { todos: [], filter: "all", }; function todoReducer(state, action) { switch (action.type) { case "ADD_TODO": return { ...state, todos: [ ...state.todos, { id: Date.now(), text: action.payload, completed: false, }, ], }; case "TOGGLE_TODO": return { ...state, todos: state.todos.map((todo) => todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo ), }; case "DELETE_TODO": return { ...state, todos: state.todos.filter((todo) => todo.id !== action.payload), }; case "SET_FILTER": return { ...state, filter: action.payload, }; default: return state; } } function TodoApp() { const [state, dispatch] = useReducer(todoReducer, initialState); const addTodo = (text) => { dispatch({ type: "ADD_TODO", payload: text }); }; const toggleTodo = (id) => { dispatch({ type: "TOGGLE_TODO", payload: id }); }; const deleteTodo = (id) => { dispatch({ type: "DELETE_TODO", payload: id }); }; const setFilter = (filter) => { dispatch({ type: "SET_FILTER", payload: filter }); }; return ( <div> <AddTodo onAdd={addTodo} /> <TodoList todos={state.todos} onToggle={toggleTodo} onDelete={deleteTodo} /> <FilterButtons filter={state.filter} onFilterChange={setFilter} /> </div> ); }
🔧 Advanced Patterns
Lazy Initialization:
function init(initialCount) { return { count: initialCount }; } function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; case "reset": return init(action.payload); default: throw new Error(); } } function Counter({ initialCount }) { const [state, dispatch] = useReducer(reducer, initialCount, init); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: "reset", payload: initialCount })} > Reset </button> </> ); }
Async Actions:
function userReducer(state, action) { switch (action.type) { case "FETCH_USER_START": return { ...state, loading: true, error: null }; case "FETCH_USER_SUCCESS": return { ...state, user: action.payload, loading: false }; case "FETCH_USER_ERROR": return { ...state, error: action.payload, loading: false }; default: return state; } } function UserProfile({ userId }) { const [state, dispatch] = useReducer(userReducer, { user: null, loading: false, error: null, }); useEffect(() => { const fetchUser = async () => { dispatch({ type: "FETCH_USER_START" }); try { const user = await fetchUserAPI(userId); dispatch({ type: "FETCH_USER_SUCCESS", payload: user }); } catch (error) { dispatch({ type: "FETCH_USER_ERROR", payload: error.message }); } }; fetchUser(); }, [userId]); if (state.loading) return <div>Loading...</div>; if (state.error) return <div>Error: {state.error}</div>; if (!state.user) return <div>No user found</div>; return <div>Welcome, {state.user.name}!</div>; }
🎯 When to Use useReducer
Use useReducer when:
- State logic is complex
- State has multiple sub-values
- State updates depend on previous state
- You want to centralize state logic
Use useState when:
- State is simple (boolean, string, number)
- State updates are independent
- State logic is straightforward
⚠️ Best Practices
- Keep reducers pure - no side effects
- Use descriptive action types
- Include payload in actions for data
- Handle all cases in switch statement
- Use TypeScript for better type safety
- Extract complex logic into separate functions
🔄 Comparison with useState
useState (Simple):
const [count, setCount] = useState(0); setCount(count + 1);
useReducer (Complex):
const [state, dispatch] = useReducer(reducer, { count: 0 }); dispatch({ type: "increment" });
111 / 111 videos100% complete
Course Completed!
Great job! You've finished all videos.
Welcome to the Course
Intro to The Course
3:33How to Learn This Course
3:02What is React and Why You Should Learn It?
4:14Getting Started with React
Installing Nodejs
3:03Setting up a React Development Environment
4:30VSCode Extensions
3:17JavaScript Refresher - All JS You Need To Know Before React
Functions
5:39Ternary and Logical Operators
7:21Objects and Arrays
7:11Map and Filter Functions
7:15Array Function Key Prop
3:13String Templating
4:27Basic React Concepts
React Project Folder Structure
6:55An Intro To JSX
10:33What is the App Component?
2:46How to use Components?
10:23Lists in React
9:45CSS in React
9:10Component Project - Build A Simple Website
First React Project
3:34Making A Navbar
7:11Displaying Images
7:11Making the About Us Section
2:35Creating A Footer
3:38Intro To States In React
What is the useState Hook?
10:38What is the useState Hook? Part 2
4:42What is the useState Hook? Part 3
14:50Intro React Project - Task Tracker App
Beginner Project - Task Tracker App
35:03React Component Lifecycle
The Virtual Dom
1:50React Component Lifecycle
1:42The useEffect Hook
15:40The useEffect Hook Part 2
8:41Routing in React
React Router
14:05React Router Part 2
14:28Advanced Forms In React
Forms in React - React Hook Form
25:36State Management
Intro To State Management - Global States
18:37Beginner Project - Build A Blog App
Intermediate Project - Build A Blog App
40:40Intermediate Project - Build A Blog App Part 2
26:57Other Useful React Hooks
Rules of Hooks
4:05Learn the useReducer Hook
9:54Learn the useRef Hook
12:03Making Your Own Custom Hook
12:10